<!--
 * @Author: luosi 1297957337@qq.com
 * @Date: 2024-11-14 14:12:51
 * @LastEditors: luosi 1297957337@qq.com
 * @LastEditTime: 2025-01-09 11:13:10
 * @FilePath: \sr_system_manager_ui\src\views\project\components\ChangeReview\index.vue
 * @Description: 变更审核
-->

<template>
  <div class="change-review">
    <div class="title">{{ projectName }}</div>
    <div class="content">
      <el-form :model="form" label-width="auto">
        <el-form-item label="变更类型">
          <div>{{ detail?.changeTypeName }}</div>
        </el-form-item>
        <el-form-item v-if="detail?.changeType?.includes(2)" label="项目变更前时间">
          <div>{{ detail?.delayBeforeDTOList?.[0]?.endTime }}</div>
        </el-form-item>
        <el-form-item v-if="detail?.changeType?.includes(2)" label="项目变更后时间">
          <div class="text-[#F53F3F]">{{ detail?.delayAfterDTOList?.[0]?.endTime }}</div>
        </el-form-item>
        <el-form-item label="变更原因">
          <div class="break-all">{{ detail?.changeReason }}</div>
        </el-form-item>
        <el-form-item label="变更材料">
          <div w-full>
            <el-segmented v-model="previewType" :options="opts" style="margin-bottom: 1rem" />
            <FilePreviewMultiple v-if="previewType === 1" :fileList="detail.attachmentFileInfoDTOList || []" />
            <el-table border v-else :data="detail.attachmentFileInfoDTOList || []" style="width: 100%">
              <el-table-column prop="name" label="文件名称" min-width="540">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-image :src="thumbnail(row.url)" lazy loading="lazy" fit="cover"
                      class="w-[16px] h-[16px] mr-[6px] flex-none" />
                    <div class="mr-[16px] text-[#1D2129] text-[14px]">{{ row?.name }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="createdByName" label="上传人" min-width="240" />
              <el-table-column prop="createdTime" label="上传时间" min-width="240">
                <template #default="{ row }">
                  <div>{{ formateDate(row.createdTime).format('YYYY-MM-DD HH:mm') }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240">
                <template #default="{ row }">
                  <el-button link type="primary" @click="handleDownload(row)">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item v-if="detail?.changeType?.includes(1) || detail?.changeType?.includes(4)" label="变更前">
          <el-table v-if="detail?.changeType?.includes(1)" border :data="detail?.memberBeforeDTOList || []"
            style="width: 100%">
            <el-table-column prop="key" label="署名顺序" min-width="60">
              <template #default="{ $index }">
                <div>{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" min-width="100" />
            <el-table-column prop="sex" label="性别" min-width="60">
              <template #default="{ row }">
                <div>{{ sexMap[row.sex as keyof typeof sexMap] }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="birth" label="出生年月" min-width="100">
              <template #default="{ row }">
                <div>{{ formateDate(row.createdTime).format('YYYY-MM-DD') }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="titleName" label="职称" min-width="100" />
            <el-table-column prop="researchDirection" label="研究专长" min-width="100" />
            <el-table-column prop="degreeName" label="学位" min-width="100" />
            <el-table-column prop="jobResponsibilities" label="承担类型" min-width="100" />
            <el-table-column prop="workUint" label="工作单位" min-width="100" />
          </el-table>
          <el-table v-if="detail?.changeType?.includes(4)" border :data="detail?.fundingBeforeDTOList || []"
            show-summary style="width: 100%" :summary-method="getSummaries">
            <el-table-column prop="key" label="序号" width="48">
              <template #default="{ $index }">
                <div>{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="budgetAccountName" label="预算科目" />
            <el-table-column prop="fundingProportion" label="经费占比">
              <template #default="{ row }">
                <div>{{ row.fundingProportion }}%</div>
              </template>
            </el-table-column>
            <el-table-column prop="fundingProportion" label="预算经费（万元）" />
            <el-table-column prop="memo" label="备注（计算依据与说明）" />
          </el-table>
        </el-form-item>
        <el-form-item v-if="detail?.changeType?.includes(1) || detail?.changeType?.includes(4)" label="变更后">
          <el-table v-if="detail?.changeType?.includes(1)" border :data="detail?.memberAfterDTOList || []"
            style="width: 100%">
            <el-table-column prop="key" label="署名顺序" min-width="60">
              <template #default="{ $index }">
                <div>{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" min-width="100" />
            <el-table-column prop="sex" label="性别" min-width="60">
              <template #default="{ row }">
                <div>{{ sexMap[row.sex as keyof typeof sexMap] }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="birth" label="出生年月" min-width="100">
              <template #default="{ row }">
                <div>{{ formateDate(row.createdTime).format('YYYY-MM-DD') }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="titleName" label="职称" min-width="100" />
            <el-table-column prop="researchDirection" label="研究专长" min-width="100" />
            <el-table-column prop="degreeName" label="学位" min-width="100" />
            <el-table-column prop="jobResponsibilities" label="承担类型" min-width="100" />
            <el-table-column prop="workUint" label="工作单位" min-width="100" />
          </el-table>
          <el-table v-if="detail?.changeType?.includes(4)" border :data="detail?.fundingAfterDTOList || []" show-summary
            style="width: 100%" :summary-method="getSummaries">
            <el-table-column prop="key" label="序号" width="48">
              <template #default="{ $index }">
                <div>{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="budgetAccountName" label="预算科目" />
            <el-table-column prop="fundingProportion" label="经费占比">
              <template #default="{ row }">
                <div>{{ row.fundingProportion }}%</div>
              </template>
            </el-table-column>
            <el-table-column prop="fundingProportion" label="预算经费（万元）" />
            <el-table-column prop="memo" label="备注（计算依据与说明）" />
          </el-table>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <QuickText v-model="form.message" style="width: 100%" />
        </el-form-item>
        <el-form-item label="相关文件">
          <FileUpload v-model="form.files" drag :limit="20" :is-show-tip="false" width="400px" />
        </el-form-item>
      </el-form>
      <div class="h-[72px]" />
    </div>
    <div class="footer">
      <el-button type="primary" @click="handleEdit">编辑</el-button>
      <el-button v-loading="rejectLoading" @click="onReject">驳回</el-button>
      <el-button v-loading="approveLoading" type="primary" @click="onApprove">通过</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import QuickText from '@/components/QuickText/index.vue'
import { projectChangeApproveApi, projectChangeDetailApi, projectChangeRejectApi } from '@/api/project'
import { BaseSuccessRespDTO, ProjectChangeDetailVO } from '@/api/project/types';
import formateDate from '@/utils/formateDate';
import FilePreviewMultiple from '@/components/FilePreviewMultiple/index.vue'
import { sexMap } from '@/utils/constText'
import { thumbnail } from '@/utils/utils'

const { proxy } = getCurrentInstance()

const router = useRouter()
const route = useRoute()
const projectId = computed(() => route.query.projectId)
const projectName = computed(() => route.query.projectName)
const previewType = ref(1)
const opts = [
  { label: '预览', value: 1 },
  { label: '列表', value: 2 },
]

const form = ref({
  message: '',
  files: []
})

const detail = ref<ProjectChangeDetailVO>({})

const { run: getDetail } = useRequest(() => projectChangeDetailApi({
  projectId: projectId.value
}), {
  manual: true,
  onSuccess: (res: ProjectChangeDetailVO) => {
    detail.value = res || {}
  }
})

const { run: approve, loading: approveLoading } = useRequest(() => projectChangeApproveApi({
  projectId: projectId.value as string,
  changeId: detail.value?.id as string,
  changeType: detail.value?.changeType as number[],
  message: form.value.message,
  fileIds: form.value.files?.map(item => item.id) || [],
}), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      ElMessage({
        message: '通过成功!',
        type: 'success',
        plain: true,
      })
      proxy.$tab.closePage()
    }
  }
})

const { run: reject, loading: rejectLoading } = useRequest(() => projectChangeRejectApi({
  projectId: projectId.value as string,
  changeId: detail.value?.id as string,
  changeType: detail.value?.changeType as number[],
  message: form.value.message,
  fileIds: form.value.files?.map(item => item.id) || [],
}), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      ElMessage({
        message: '驳回成功!',
        type: 'success',
        plain: true,
      })
      proxy.$tab.closePage()
    }
  }
})

const getSummaries = (param) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0 || index === 4) {
      sums[index] = ''
      return
    }
    if (index === 1) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}${index === 2 ? '%' : ''}`
    } else {
      sums[index] = ''
    }
  })

  return sums
}

const handleEdit = () => {
  router.push({ path: '/project/mine/initiateChange', query: { projectId: projectId.value, projectName: projectName.value, type: 'edit' } })
}

const onApprove = () => {
  if (!form.value?.message) return ElMessage.error('请填写审核意见')
  approve()
}

const onReject = () => {
  if (!form.value?.message) return ElMessage.error('请填写审核意见')
  reject()
}

const handleDownload = (file) => {
  proxy.$download.downloadFileSync(file?.url, file?.name)
}

onMounted(() => {
  getDetail()
})
</script>

<style lang="scss" scoped>
.change-review {
  --at-apply: bg-white min-h-full;

  .title {
    --at-apply: py-16px pl-20px text-[16px] font-bold border-b-[1px] border-b-solid border-[#E5E6EB];
  }

  .content {
    --at-apply: p-[20px] bg-white;
  }

  :deep(.el-textarea__inner) {
    min-height: 120px !important;
  }
}

.footer {
  --at-apply: fixed bottom-0 left-0 w-full h-[72px] leading-[72px] text-center border-t-solid border-t-[1px] border-[#E5E6EB] bg-white z-[100];
}
</style>